package params

import (
	"strconv"
	"strings"
)

type Variable struct {
	Name  string
	Value []string
}

// 去除空格
func (v *Variable) Trim() string {
	return strings.TrimSpace(v.Value[0])
}

// 获取字符串
func (v *Variable) String() string {
	return v.Value[0]
}

// 分割字符串
func (v *Variable) Split(sep string) []*Variable {
	values := strings.Split(v.Value[0], sep)
	vars := make([]*Variable, len(values))
	for i, value := range values {
		vars[i] = &Variable{Name: v.Name, Value: []string{value}}
	}
	return vars
}

// 拼接字符串
func (v *Variable) Join(sep string) string {
	return strings.Join(v.Value, sep)
}

// 限制值
func (v *Variable) Lmt(def string, options ...string) string {
	for _, option := range options {
		if v.Value[0] == option {
			return option
		}
	}
	return def
}

// 转换为 int
func (v *Variable) Int() (int, error) {
	i, err := strconv.Atoi(v.Value[0])
	if err != nil {
		return 0, err
	}
	return i, nil
}

// 强制转换为 int 默认值为0
func (v *Variable) MustInt() int {
	i, err := v.Int()
	if err != nil {
		return 0
	}
	return i
}

// 转换为 int64
func (v *Variable) Int64() (int64, error) {
	i, err := strconv.ParseInt(v.Value[0], 10, 64)
	if err != nil {
		return 0, err
	}
	return i, nil
}

// 强制转换为 int64 默认值为0
func (v *Variable) MustInt64() int64 {
	i, err := v.Int64()
	if err != nil {
		return 0
	}
	return i
}

// 转换为 float64
func (v *Variable) Float() (float64, error) {
	f, err := strconv.ParseFloat(v.Value[0], 64)
	if err != nil {
		return 0, err
	}
	return f, nil
}

// 强制转换为 float64 默认值为0
func (v *Variable) MustFloat() float64 {
	f, err := v.Float()
	if err != nil {
		return 0
	}
	return f
}

// 转换为 bool
func (v *Variable) Bool() (bool, error) {
	b, err := strconv.ParseBool(v.Value[0])
	if err != nil {
		return false, err
	}
	return b, nil
}

// 强制转换为 bool 默认值为 false
func (v *Variable) MustBool() bool {
	b, err := v.Bool()
	if err != nil {
		return false
	}
	return b
}

// 转换为数组
func (v *Variable) Arr() []*Variable {
	vars := make([]*Variable, len(v.Value))
	for i, value := range v.Value {
		vars[i] = &Variable{Name: v.Name, Value: []string{value}}
	}
	return vars
}
